%% @author wenqi_zheng
%% @doc @todo Add description to examples2.


-module(examples2).

%% ====================================================================
%% API functions
%% ====================================================================
-export([start/0, loop/0]).

-define(TCP_OPTIONS, [
	binary, 
	{packet, 4}, 
	{active, once}, 
	{exit_on_close, true}, 
	{reuseaddr, true} ]).


start() ->
	Pid = spawn_link(?MODULE, loop, []),
	{ok, Listen} = gen_tcp:listen(2345, ?TCP_OPTIONS),
	loop_listen(Listen, Pid).


loop_listen(Listen, Pid) ->
	{ok, Socket} = gen_tcp:accept(Listen),
	gen_tcp:controlling_process(Socket, Pid),
	loop_listen(Listen, Pid).


loop() ->
	receive
		{tcp, Socket, Bin} ->
			io:format("rcv from ~p: ~p", [Socket, Bin]),
			Answer= process(Bin), 
			gen_tcp:send(Socket, Answer),
			inet:setopts(Socket, [{active, once}]),
			loop()
	end.

process(Data)->
	io:format("~wServer received binary =~p~n",  [self(), Data]),
	Str = binary_to_term(Data),
	io:format("Server {unpacked} ~p~n", [Str]),
	Reply = lib_misc:string2value(Str),
	io:format("Server replying = ~p~n", [Reply]),
	term_to_binary(Reply).

%% ====================================================================
%% Internal functions
%% ====================================================================


